package com.cn.shuangzi.common;

import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.bean.VersionInfo;
import com.cn.shuangzi.permission.RequestPermissionViewP;
import com.cn.shuangzi.permission.RequestWritePermissionHelper;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.retrofit.SZRetrofitResponseListener;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZFileUtil;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.cn.shuangzi.util.download.SZDownloaderUtil;
import com.cn.shuangzi.view.AlertWidget;
import com.cn.shuangzi.view.sweet_alert.SweetAlertDialog;
import com.google.gson.Gson;

import java.io.File;
import java.util.Date;

/**
 * Created by CN on 2016/12/8.
 */

public class VersionUpdate {
    private VersionUpdateListener versionUpdateListener;
    private SZBaseActivity activity;

    private AlertWidget progressAlert;

    private long lastTime;
    private long lastProgress;
    private boolean isFromUser;//是否用户主动操作，留在设置中 如果有个检查更新项的话 传true
    private VersionInfo versionInfo;
    private String fileName;
    private SZXmlUtil xmlUtil;
    private int dateInterval;
    private String txtNoticeClose;
    private boolean isRequestSuccess;
    public VersionUpdate(SZBaseActivity activity) {
        this(activity, 0);
    }

    public VersionUpdate(SZBaseActivity activity, int dateInterval) {
        this(activity, dateInterval, null);
    }

    public VersionUpdate(SZBaseActivity activity, int dateInterval, VersionUpdateListener versionUpdateListener) {
        this(activity, dateInterval, versionUpdateListener,null);
    }
    public VersionUpdate(SZBaseActivity activity, int dateInterval, VersionUpdateListener versionUpdateListener,String txtNoticeClose) {
        this.activity = activity;
        this.versionUpdateListener = versionUpdateListener;
        this.dateInterval = dateInterval;
        this.txtNoticeClose = txtNoticeClose;
        xmlUtil = new SZXmlUtil("update");
        isRequestSuccess = false;
    }

    public void setTxtNoticeClose(String txtNoticeClose) {
        this.txtNoticeClose = txtNoticeClose;
    }

    /**
     * 检查是否有新版本
     *
     * @param isFromUser 是否用户主动操作
     */
    public VersionUpdate checkNewVersion(boolean isFromUser) {
        this.isFromUser = isFromUser;
        //是否有下载好的新版本
        requestNewVersion();
        return this;
    }

    private void setUpdateShowDate() {
        xmlUtil.put("date", System.currentTimeMillis());
    }

    private void removeUpdateShowDate() {
        xmlUtil.remove("date");
    }

    private boolean isShowUpdate() {
        if (versionInfo == null) {
            return false;
        }
        if (versionInfo.isLastVersion()) {
            if(isFromUser){
                return true;
            }
            if (versionInfo.isRequired()) {
                return true;
            }
            if (dateInterval <= 0) {
                return isShowUpdate(7);
            } else {
                return isShowUpdate(dateInterval);
            }
        }
        return false;
    }

    public boolean isShowUpdate(int dateInterval) {
        long date = xmlUtil.getLong("date");
        if (date <= 0) {
            return true;
        } else {
            return SZDateUtil.getDayDistance(new Date(date), new Date()) >= dateInterval;
        }
    }

    public VersionUpdate showUpdateAlert(final VersionInfo versionInfo) {
        final AlertWidget alertWidget = new AlertWidget(activity);
        alertWidget.show(R.layout.layout_update);
        alertWidget.setCancelable(false);
        TextView txtVersion = alertWidget.getWindow().findViewById(R.id.txtVersion);
        TextView txtContent = alertWidget.getWindow().findViewById(R.id.txtContent);
        TextView txtClose = alertWidget.getWindow().findViewById(R.id.txtClose);
        TextView txtUpdate = alertWidget.getWindow().findViewById(R.id.txtUpdate);
        final CheckBox chkBox = alertWidget.getWindow().findViewById(R.id.chkBox);
        if (dateInterval > 0) {
            chkBox.setText(dateInterval + "天内不再提示");
        }
        if(isFromUser){
            alertWidget.getWindow().findViewById(R.id.lltIgnore).setVisibility(View.GONE);
        }
        txtUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (versionInfo.isRequired()) {
                    if (!SZValidatorUtil.isValidString(versionInfo.getDownloadUrl())) {
                        SZUtil.launchAppStoreDetail(activity, activity.getPackageName(), null);
                        return;
                    }
                    activity.requestPermission(new RequestWritePermissionHelper(activity, true, new RequestPermissionViewP() {
                        @Override
                        public void onPermissionRequestSuccess(String[] permissionName) {
                            alertWidget.close();
                            downloadApk();
                            showProgressAlert();
                            if (versionUpdateListener != null) {
                                versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                            }
                        }

                        @Override
                        public void onRequestPermissionAlertCancelled(String[] permissionName) {
                            SZToast.errorLong("同意文件读写权限后，才能下载更新哦~");
                        }
                    }));

                } else {
                    if (SZValidatorUtil.isValidString(versionInfo.getDownloadUrl())) {
                        activity.requestPermission(new RequestWritePermissionHelper(activity, true, new RequestPermissionViewP() {
                            @Override
                            public void onPermissionRequestSuccess(String[] permissionName) {
                                alertWidget.close();
                                downloadApk();
                                showProgressAlert();
                                if (versionUpdateListener != null) {
                                    versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                                }
                            }

                            @Override
                            public void onRequestPermissionAlertCancelled(String[] permissionName) {
                                SZToast.errorLong("同意文件读写权限后，才能下载更新哦~");
                            }
                        }));
                    }else {
                        alertWidget.close();
                        SZUtil.launchAppStoreDetail(activity, activity.getPackageName(), null);
                        if (!isFromUser) {
                            showNoticeAlert();
                        }
                        if (versionUpdateListener != null) {
                            versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                        }
                    }
                }
            }
        });
        txtClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (versionInfo.isRequired()) {
                    alertWidget.close();
                    if (versionUpdateListener != null) {
                        versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                    }
                    SZApp.getInstance().removeAndFinishAllActivity();
                } else {
                    if(!isFromUser) {
                        if (chkBox.isChecked()) {
                            setUpdateShowDate();
                        } else {
                            removeUpdateShowDate();
                        }
                    }
                    alertWidget.close();
                    if (versionUpdateListener != null) {
                        versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                    }
                    if (!isFromUser) {
                        showNoticeAlert();
                    }
                }
            }
        });
        ImageView imgClose = alertWidget.getWindow().findViewById(R.id.imgClose);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isFromUser) {
                    if (chkBox.isChecked()) {
                        setUpdateShowDate();
                    } else {
                        removeUpdateShowDate();
                    }
                }
                alertWidget.close();
                if (versionUpdateListener != null) {
                    versionUpdateListener.onUpdateAlertDismiss(versionInfo);
                }
                if (!isFromUser) {
                    showNoticeAlert();
                }
            }
        });
        if (versionInfo.isRequired()) {
            chkBox.setVisibility(View.GONE);
            imgClose.setVisibility(View.GONE);
            txtClose.setVisibility(View.VISIBLE);
            txtClose.setText("不更新，退出");
        } else {
            if(!isFromUser) {
                chkBox.setVisibility(View.VISIBLE);
                txtClose.setText("忽略本次");
            }
            txtClose.setVisibility(View.GONE);
            imgClose.setVisibility(View.VISIBLE);
        }
        String versionName = versionInfo.getVersionText();
        if (versionName.contains("V") || versionName.contains("v")) {
            txtVersion.setText(versionName);
        } else {
            txtVersion.setText("V" + versionName);
        }
        if (SZValidatorUtil.isValidString(versionInfo.getDescribe())) {
            txtContent.setText(versionInfo.getDescribe());
        }
        return this;
    }

    private void showNoticeAlert(){
        SweetAlertDialog sweetAlertDialog;
        if(versionInfo!=null&&versionInfo.getNotice()!=null&&SZValidatorUtil.isValidString(versionInfo.getNotice().getContent())){
            final VersionInfo.NoticeInfo noticeInfo = versionInfo.getNotice();
            if(noticeInfo.isRequired()){
                String okText = SZValidatorUtil.isValidString(txtNoticeClose)?txtNoticeClose:"知道了，稍后再用";
                sweetAlertDialog = activity.showWarningAlert(noticeInfo.getTitle(), noticeInfo.getContent(),okText,null, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        if(sweetAlertDialog!=null) {
                            sweetAlertDialog.cancel();
                        }
                        if(versionUpdateListener!=null){
                            versionUpdateListener.onClickCloseNoticeAlert();
                        }else{
                            SZApp.getInstance().removeAndFinishAllActivity();
                        }
                    }
                }).showCancelButton(false);
                sweetAlertDialog.setCancelable(false);
            }else {
                String notice = xmlUtil.getString("notice");
                if(!noticeInfo.getContent().equals(notice)) {
                    activity.showAlert(SweetAlertDialog.NORMAL_TYPE, noticeInfo.getTitle(), noticeInfo.getContent(), "知道了", null, "已确认，不再提示", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            xmlUtil.put("notice", noticeInfo.getContent());
                            sweetAlertDialog.cancel();
                        }
                    }, true);
                }
            }
        }
    }
    private String requestTag;
    public VersionUpdate requestNewVersion() {
        if(requestTag!=null) {
            SZRetrofitManager.getInstance().cancelDisposable(requestTag);
        }
        requestTag = String.valueOf(System.currentTimeMillis());
        SZRetrofitManager.getInstance().request(SZRetrofitManager.getInstance().getSZRequest().getNewVersionInfoV2( "ANDROID", SZUtil.getVersionCode())
                ,requestTag, new SZRetrofitResponseListener.SimpleSZRetrofitResponseListener() {
                    @Override
                    public void onSuccess(String data) {
                        isRequestSuccess = true;
                        versionInfo = new Gson().fromJson(data, VersionInfo.class);
                        if (versionInfo.isLastVersion()) {
                            if (isShowUpdate()) {
                                showUpdateAlert(versionInfo);
                            } else {
                                if (!isFromUser) {
                                    showNoticeAlert();
                                }
                                if (versionUpdateListener != null) {
                                    versionUpdateListener.onIgnoreUpdateAlertShow(versionInfo, data);
                                }
                            }
                        } else {
                            if (isFromUser) {
                                SZToast.info("当前已经是最新版本！");
                            }else{
                                showNoticeAlert();
                            }
                        }
                        if (versionUpdateListener != null) {
                            versionUpdateListener.onSuccess(versionInfo, data);
                        }

                    }

                    @Override
                    public void onNetError(int errorCode, String errorMsg) {
                        if (versionUpdateListener != null) {
                            versionUpdateListener.onNetError(errorCode, errorMsg);
                        }
                    }
                });
        return this;
    }

    public boolean isRequestSuccess() {
        return isRequestSuccess;
    }

    private void showProgressAlert() {
        if (activity == null)
            return;
        if (progressAlert == null) {
            progressAlert = new AlertWidget(activity);
        }
        progressAlert.show(R.layout.alert_download_progress);
        progressAlert.setCancelable(false);
    }


    private void downloadApk() {
        fileName = String.valueOf(versionInfo.getDownloadUrl().hashCode() + ".apk");
        SZDownloaderUtil.download(versionInfo.getDownloadUrl(), fileName, new SZDownloaderUtil.HttpDownloadListener() {
            @Override
            public void onProgress(long bytesRead, long contentLength, boolean done) {
                long progress = (100 * bytesRead) / contentLength;
                if (System.currentTimeMillis() - lastTime >= 500 && progress >= lastProgress && !done) {
                    //设置更新进度条
                    updateAlertProgress((int) progress);
                    lastTime = System.currentTimeMillis();
                    lastProgress = progress;
                    SZUtil.log("progress:" + lastProgress);
                }
            }

            @Override
            public void onStart(long bytesRead, long contentLength, boolean done) {
                lastTime = System.currentTimeMillis();
                lastProgress = 0;
                updateAlertProgress((int) lastProgress);
            }

            @Override
            public void onFinish(long bytesRead, long contentLength, boolean done) {

                updateAlertProgress(100);
                SZUtil.installApk(new File(SZFileUtil.getInstance().getDownloadPathName(), fileName));
                SZUtil.log("===========完成了===========");
            }

            @Override
            public void onError() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateAlertProgress(-2);
                    }
                });
            }
        });
    }

    private void updateAlertProgress(int progress) {
        if (progressAlert == null) {
            showProgressAlert();
        }
        if (progressAlert != null) {
            ProgressBar progressBar = progressAlert.getWindow().findViewById(R.id.noti_progress_bar);
            TextView txtProgress = progressAlert.getWindow().findViewById(R.id
                    .noti_progress_textview);
            TextView noti_textview = progressAlert.getWindow().findViewById(R.id
                    .noti_textview);
            TextView txtInstall = progressAlert.getWindow().findViewById(R.id
                    .txtInstall);
            progressBar.setMax(100);
            if (progress >= 0) {
                noti_textview.setText("下载中...");
                progressBar.setProgress(progress);
                txtProgress.setText(progress + "%");
            }
            if (progress == 100) {
                noti_textview.setText("下载完成");
                txtInstall.setVisibility(View.VISIBLE);
                txtInstall.setText("安装");
                txtInstall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SZUtil.installApk(new File(SZFileUtil.getInstance().getDownloadPathName(), fileName));
                    }
                });
            } else if (progress == -2) {
                SZToast.error("网络不给力，下载出错！");
                noti_textview.setText("网络不给力，下载出错");
                txtInstall.setVisibility(View.VISIBLE);
                txtInstall.setText("重新下载");
                txtInstall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downloadApk();
                    }
                });
            }
        }
    }

    public interface VersionUpdateListener {
        void onSuccess(VersionInfo versionInfo, String data);

        void onNetError(int errorCode, String errorMsg);

        void onClickCloseNoticeAlert();

        void onUpdateAlertDismiss(VersionInfo versionInfo);

        void onIgnoreUpdateAlertShow(VersionInfo versionInfo, String data);
    }
}
